/**
 * @author benny.zheng
 * @data 2016-06-06
 * @description 本文件用于方便复制粘贴UI模块之用，请更新这里的说明
 *              另外，考虑到一般是放在js/src/pages/page-name/main.js，因此使用../../
 *              如果不是这个目录，请更改成正确的相对路径
 */
//----------------require--------------

var viewport = require("mlib/dom/viewport"); // viewport
var base = require("mlib/comp/base"); // 基础对象
var parseModule = require("mlib/dom/parseModule"); // 页面模块自动解析
var wechat = require("../plugin/wx/wx-api");

var ajax = require("mlib/io/ajax");
var closest = require("mlib/dom/closest");
var siblings = require('mlib/dom/siblings');
var currency = require("../plugin/util/currency");
var weuiAlert = require('../layer/weuialert');
var touch = require("mlib/evt/touch");

module.exports = function(node, opts) {
    //-----------声明模块全局变量-------------
    var nodeList = null; // 存储所有关键节点
    var that = base();
    var data = null;
	var m_balance = null; // 卡余额
	var m_cardnum = null; // 卡号码
	var m_cardid = null; // 卡号ID
	var m_money = null;  // 充值金额
	var isOtherMoney = false ;

    //-------------事件响应声明---------------
    var evtFuncs = {
		docHanddle:function(e){
			var target = e.target;
			e.delegateTarget = closest(target, ".m-select", true);
			if (e.delegateTarget){
				var curtarget = closest(target, ".select-option", true);
				var searChoese  = closest(target, ".select-box", true);
				if(searChoese && !nodeList.dropdown.classList.contains("hidden")){
					custFuncs.hide();
				}else if(curtarget){					
					curtarget.classList.add("active");					
					m_cardnum = curtarget.dataset.cardnum;
					m_cardid = curtarget.dataset.cardid;
					m_balance = curtarget.dataset.balance;
					nodeList.selectinput.innerHTML = m_cardnum || '';
					nodeList.mbalance.innerHTML = m_balance || '';	
					siblings(curtarget, 'li').forEach(function(item){
						item.classList.remove("active");
					});
					custFuncs.hide();
				}else{
					custFuncs.show();
				}
				
			} else{
				custFuncs.hide();
			}
		},		
		selectMoney:function(e){
			var target = closest(e.target, ".money-item", true);
			target.classList.add("money-item-active");
			[].slice.call(nodeList.moneylist.querySelectorAll(".money-item")).forEach(function(item){
				if(item==target){
					item.classList.add("money-item-active");
					m_money = item.dataset.money;
					if(item.dataset.money==0){
						isOtherMoney = true ;
						nodeList.otheramount.value = '';
						nodeList.otherwrap.style.display = 'block';
					}else{
						isOtherMoney = false ;
						nodeList.otherwrap.style.display = 'none';
					}
				}else{
					item.classList.remove("money-item-active");
				}
			});
		},
		recharge:function(){			
			if(isOtherMoney){
				var inputmoney = nodeList.otheramount.value;
				if(custFuncs.isNumeric(inputmoney)){
					inputmoney = custFuncs.valBetween(parseFloat(inputmoney),0,5000);	
					m_money = currency(inputmoney,2);
				}else if(inputmoney==""){
					weuiAlert("请填写金额");	return;
				}else{
					weuiAlert("请填写正确的金额");	return;
				}
			}
			var params = {};
			params["cardid"] = m_cardid;
			params["balance"] = m_balance;
			params["money"] = m_money;
			if(that.isLock()) {
				return;
			}
			that.lock();
			 ajax({
				 url: data.recharge+data.ocid,
				data: params, // 仅method=post时生效，如果传入json对象会被转换成queryString，如果传入字符串则会原样发送
				method: "post", // 默认是get
				onSuccess: function(res) {
					that.unLock();	
					if(res.error==0){
						location.href = res.url;
					}else{
						weuiAlert(res.msg);
					}
				},
				onError: function(xmlHttp) {
                    that.unLock();	
				}, // 当访问出错，比如网络连接不上、解析内容失败时触发，超时也会触发
				onTimeout: function(xmlHttp) { }, // 超时触发
				onAbort: function() {} // 网络中断时触发
			 });
		},
		limitnumber:function(e){
			var numval = this.value;
			if(!custFuncs.isNumeric(numval)){				
				e.preventDefault();
			}
		}
	}

    //-------------子模块实例化---------------
    var initMod = function() {
		if(data.cardlist.length>0){
			m_cardnum = data.cardlist[0].cardnum;
			m_cardid = data.cardlist[0].cardid;
			m_balance = data.cardlist[0].balance;
		}
		if(data.moneylist.length>0){
			m_money = data.moneylist[0].value;
		}
         wechat('off').init();
    }

    //-------------绑定事件------------------
    var bindEvents = function() {
		if(data.cardlist.length>1){
			touch.on(document.body, 'touchstart',evtFuncs.docHanddle);
		}		 
		 touch.on(nodeList.moneylist, 'tap',".money-item",evtFuncs.selectMoney);
		 touch.on(nodeList.button, 'touchstart',evtFuncs.recharge);
		 nodeList.otheramount.addEventListener("input",evtFuncs.limitnumber,false);
		 
	}

    //-------------自定义函数----------------
    var custFuncs = {
           show:function(){
			   nodeList.dropdown.classList.remove("hidden");
		   },  
		   hide:function(){
			   nodeList.dropdown.classList.add("hidden");
		   },
		   valBetween:function(v, min, max){
			   return (Math.min(max, Math.max(min, v)));
		   },
		   isNumeric:function(value){
			   return !isNaN(parseFloat(value)) && isFinite(value);
		   }
    }

    //-------------一切从这开始--------------
    var init = function(_data) {

        data = _data;
        // 根据数据初始化模块
        // opts["render"]({ "title": data["title"] });

        // 找到所有带有node-name的节点
        nodeList = parseModule(node);
		//console.log(nodeList);
        // 子模块实例化
        initMod();
        // 绑定事件
        bindEvents();


    }

    //---------------暴露API----------------
    that.init = init;

    return that;
};